# -*- coding: utf-8 -*-

import pika
from .config import *

class RabbitConnection(object):
    """
    实例化 Rabbitmq 连接对象， 默认读取config 中的配置
    """

    def __init__(self, host=None, port=None, user=None, password=None):
        self.connection = None
        self.host = host if host else RABBIT_HOST
        self.port = port if port else RABBIT_PORT
        self.user = user if user else RABBIT_USER
        self.password = password if password else RABBIT_USER_PASSWORD

    def get_connection(self):
        # mq用户名和密码
        credentials = pika.PlainCredentials(self.user, self.password)

        # 虚拟队列需要指定参数 virtual_host，如果是默认的可以不填。
        connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=self.host, port=self.port, credentials=credentials)
        )
        self.connection = connection
        return connection.channel()
